// 简单的HTTP服务器，用于托管前端文件
const http = require('http');
const fs = require('fs');
const path = require('path');

// 服务器配置
const PORT = 3000;
const HOST = 'localhost';
const PUBLIC_DIR = path.join(__dirname, 'matrix_html');

// 创建HTTP服务器
const server = http.createServer((req, res) => {
    console.log(`${req.method} ${req.url}`);
    
    // 解析请求路径
    let filePath = path.join(PUBLIC_DIR, req.url);
    
    // 如果路径是目录，默认访问index.html
    if (fs.existsSync(filePath) && fs.lstatSync(filePath).isDirectory()) {
        filePath = path.join(filePath, 'index.html');
    }
    
    // 如果路径不存在，返回404
    if (!fs.existsSync(filePath)) {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('404 Not Found');
        return;
    }
    
    // 读取文件内容
    fs.readFile(filePath, (err, data) => {
        if (err) {
            res.writeHead(500, { 'Content-Type': 'text/plain' });
            res.end('500 Internal Server Error');
            return;
        }
        
        // 根据文件扩展名设置Content-Type
        const extname = path.extname(filePath);
        let contentType = 'text/html';
        
        switch (extname) {
            case '.js':
                contentType = 'text/javascript';
                break;
            case '.css':
                contentType = 'text/css';
                break;
            case '.json':
                contentType = 'application/json';
                break;
            case '.png':
                contentType = 'image/png';
                break;
            case '.jpg':
            case '.jpeg':
                contentType = 'image/jpeg';
                break;
            case '.gif':
                contentType = 'image/gif';
                break;
            case '.svg':
                contentType = 'image/svg+xml';
                break;
            case '.ico':
                contentType = 'image/x-icon';
                break;
        }
        
        // 发送响应
        res.writeHead(200, { 'Content-Type': contentType });
        res.end(data);
    });
});

// 启动服务器
server.listen(PORT, HOST, () => {
    console.log(`服务器已启动，访问地址: http://${HOST}:${PORT}`);
    console.log(`前端应用地址: http://${HOST}:${PORT}/index.html`);
    console.log(`聊天界面地址: http://${HOST}:${PORT}/module/index/mx_chat.html?topic=30000000`);
});